<template>
  <view class="form-bg">
    <view class="form-card">
      <view class="form-item">
        <text class="label">企业名称</text>
        <input v-model="form.company" placeholder="请输入企业名称" class="input" />
      </view>
      <view class="form-item">
        <text class="label">注册资本</text>
        <input v-model="form.capital" placeholder="请输入注册资本" class="input" />
      </view>
      <view class="form-item">
        <text class="label">法人代表</text>
        <input v-model="form.legalPerson" placeholder="请输入法人代表" class="input" />
      </view>
      <view class="form-item">
        <text class="label">项目标题</text>
        <input v-model="form.title" placeholder="请输入项目标题" class="input" />
      </view>
      <view class="form-item">
        <text class="label">前景描述</text>
        <textarea v-model="form.prospect" placeholder="请输入前景描述" class="textarea" />
      </view>
      <view class="form-item">
        <text class="label">具体方案</text>
        <textarea v-model="form.plan" placeholder="请输入具体方案" class="textarea" />
      </view>
      <!-- 上传执照 -->
      <view class="form-item">
        <text class="label">上传执照</text>
        <view class="image-upload">
          <view class="image-row">
            <view v-for="(item, idx) in form.licenseImgs" :key="idx" class="image-item">
              <image :src="item" class="cover-image" @click="previewImage('licenseImgs', idx)" />
              <view class="delete-icon" @click.stop="deleteImage('licenseImgs', idx)">删除</view>
            </view>
            <view v-if="form.licenseImgs.length < 5" class="image-item add-image" @click="chooseImage('licenseImgs')">
              <text class="upload-text">+</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 上传法人身份证 -->
      <view class="form-item">
        <text class="label">上传法人身份证</text>
        <view class="image-upload">
          <view class="image-row">
            <view v-for="(item, idx) in form.idcardImgs" :key="idx" class="image-item">
              <image :src="item" class="cover-image" @click="previewImage('idcardImgs', idx)" />
              <view class="delete-icon" @click.stop="deleteImage('idcardImgs', idx)">删除</view>
            </view>
            <view v-if="form.idcardImgs.length < 5" class="image-item add-image" @click="chooseImage('idcardImgs')">
              <text class="upload-text">+</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 协议勾选 -->
      <view class="form-item agreement">
        <checkbox-group @change="onAgreeChange">
          <checkbox value="agree" :checked="form.agree" />
        </checkbox-group>
        <text>本人承诺所填信息真实有效，愿意承担法律责任</text>
      </view>
    </view>
    <button class="submit-btn" @click="submit">{{isEdit ? '保存修改' : '提交审核'}}</button>
  </view>
</template>

<script>
import cfg from '@/common/config.js'
import api from '@/common/api/index.js'
export default {
  data() {
    return {
      form: {
        company: '',
        capital: '',
        legalPerson: '',
        title: '',
        prospect: '',
        plan: '',
        licenseImgs: [],
        idcardImgs: [],
        agree: false
      },
      uploadUrl: cfg.url + '/infra/file/upload', // 你的上传接口
      uploadHeader: {
        'tenant-id': '1',
        'Authorization': uni.getStorageSync('userToken') || ''
      },
      uploadFormData: {
        // 可根据实际需要传递额外参数
        path: '' // 这里可动态设置
      },
      isEdit: false,
      editId: null
    }
  },
  onLoad(query) {
    if (query.id) {
      this.isEdit = true;
      this.editId = query.id;
      // 拉取详情
      api.req(`/station/idle-publish/get?id=${query.id}`, {}, 'GET', 'JSON', false).then(res => {
        if (res.code === 0 && res.data) {
          // 兼容图片字段为字符串或数组
          let form = { ...res.data };
          form.licenseImgs = typeof form.licenseImgs === 'string' ? (form.licenseImgs ? form.licenseImgs.split(',') : []) : (form.licenseImgs || []);
          form.idcardImgs = typeof form.idcardImgs === 'string' ? (form.idcardImgs ? form.idcardImgs.split(',') : []) : (form.idcardImgs || []);
          this.form = form;
        }
      });
    } else {
      this.isEdit = false;
      this.editId = null;
      this.resetForm();
    }
    // 动态设置上传路径
    let fileName = file.path.split('/').pop();  // 获取文件名
    let userId = this.f.storage('user_data').userId || '0';
    this.uploadFormData.path = userId + '/' + fileName;  // 在文件名前加上 userId
  },
  methods: {
    resetForm() {
      this.form = {
        company: '',
        capital: '',
        legalPerson: '',
        title: '',
        prospect: '',
        plan: '',
        licenseImgs: [],
        idcardImgs: [],
        agree: false
      };
    },
    // 选择图片并上传
    chooseImage(type) {
      // type: 'licenseImgs' 或 'idcardImgs'
      uni.chooseImage({
        count: 5 - this.form[type].length,
        success: (res) => {
          const tempFiles = res.tempFiles;
          tempFiles.forEach(file => {
            let fileName = file.path.split('/').pop();
            let userId = uni.getStorageSync('user_data')?.userId || '0';
            let filePath = userId + '/' + fileName;
            uni.uploadFile({
              url: cfg.url + '/infra/file/upload',
              filePath: file.path,
              name: 'file',
              header: {
                'tenant-id': '1',
                'Authorization': uni.getStorageSync('userToken') || '',
              },
              formData: {
                path: filePath
              },
              success: (uploadRes) => {
                let data = JSON.parse(uploadRes.data);
                if (data.code === 0) {
                  let imageUrl = data.data;
                  this.form[type].push(imageUrl);
                  console.log(this.form[type]);
                  
                } else {
                  uni.showToast({ title: '上传失败', icon: 'none' });
                }
              },
              fail: () => {
                uni.showToast({ title: '上传出错', icon: 'none' });
              }
            });
          });
        }
      });
    },
    // 删除图片
    deleteImage(type, idx) {
      this.form[type].splice(idx, 1);
    },
    // 预览图片
    previewImage(type, idx) {
      uni.previewImage({
        current: this.form[type][idx],
        urls: this.form[type]
      });
    },
    // 协议勾选
    onAgreeChange(e) {
      this.form.agree = e.detail.value.includes('agree');
    },
    // 表单提交
    submit() {
      if (!this.form.company || !this.form.capital || !this.form.legalPerson || !this.form.title || !this.form.prospect || !this.form.plan) {
        uni.showToast({ title: '请填写完整信息', icon: 'none' });
        return;
      }
      if (!this.form.licenseImgs.length || !this.form.idcardImgs.length) {
        uni.showToast({ title: '请上传执照和身份证', icon: 'none' });
        return;
      }
      if (!this.form.agree) {
        uni.showToast({ title: '请勾选协议', icon: 'none' });
        return;
      }
      // 构造提交数据
      let data = { ...this.form };
      if (this.isEdit && this.editId) {
        data.id = this.editId;
        api.req('/station/idle-publish/update', data, 'POST', 'JSON', false).then(res => {
          if (res.code === 0) {
            uni.showToast({ title: '修改成功', icon: 'success' });
            setTimeout(() => {
              uni.navigateBack();
            }, 1200);
          } else {
            uni.showToast({ title: res.msg || '修改失败', icon: 'none' });
          }
        });
      } else {
        api.req('/station/idle-publish/create', data, 'POST', 'JSON', false).then(res => {
          if (res.code === 0) {
            uni.showToast({ title: '提交成功，等待审核', icon: 'success' });
            setTimeout(() => {
              uni.navigateBack();
            }, 1200);
          } else {
            uni.showToast({ title: res.msg || '提交失败', icon: 'none' });
          }
        });
      }
    }
  }
}
</script>

<style scoped>
.form-bg {
  min-height: 100vh;
  background: linear-gradient(135deg, #f7faff 0%, #e3e8f0 100%);
  padding: 0 0 120rpx 0;
}
.form-card {
  background: #fff;
  border-radius: 18rpx;
  box-shadow: 0 4rpx 24rpx rgba(86,119,252,0.08);
  margin: 36rpx 24rpx 0 24rpx;
  padding: 32rpx 24rpx 12rpx 24rpx;
}
.form-item {
  margin-bottom: 32rpx;
  border-bottom: 1px solid #f2f2f2;
  padding-bottom: 18rpx;
}
.form-item:last-child {
  border-bottom: none;
}
.label {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 10rpx;
  display: block;
  font-weight: 500;
}
.input {
  width: 100%;
  height: 44px;
  border: none;
  border-radius: 8rpx;
  padding: 0 16rpx;
  font-size: 28rpx;
  background: #f7f7f7;
  margin-top: 8rpx;
}
.textarea {
  width: 100%;
  min-height: 80px;
  border: none;
  border-radius: 8rpx;
  padding: 10rpx 16rpx;
  font-size: 28rpx;
  background: #f7f7f7;
  margin-top: 8rpx;
}
.agreement {
  display: flex;
  align-items: center;
  font-size: 24rpx;
  color: #888;
  margin-top: 10rpx;
  border-bottom: none;
}
.submit-btn {
  position: fixed;
  left: 5vw;
  bottom: 40rpx;
  width: 90vw;
  height: 48px;
  background: linear-gradient(90deg, #5677fc 0%, #6ddaa3 100%);
  color: #fff;
  font-size: 20px;
  border-radius: 12px;
  box-shadow: 0 4rpx 16rpx rgba(86,119,252,0.12);
  margin-top: 20px;
  z-index: 99;
  border: none;
}

/* 优化上传图片区域样式，参考basics.vue */
.image-upload {
  width: 100%;
  margin-top: 10rpx;
}
.image-row {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  gap: 10rpx;
}
.image-item {
  position: relative;
  width: 23%;
  height: 150rpx;
  border-radius: 8rpx;
  margin-left: 10px;
  overflow: hidden;
  background-color: #f7f7f7;
  display: flex;
  justify-content: center;
  align-items: center;
}
.cover-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 8rpx;
}
.delete-icon {
  position: absolute;
  top: 5rpx;
  right: 5rpx;
  background-color: rgba(0, 0, 0, 0.5);
  color: white;
  padding: 5rpx 10rpx;
  font-size: 20rpx;
  border-radius: 10rpx;
  cursor: pointer;
  z-index: 2;
}
.upload-text {
  font-size: 48rpx;
  color: #888;
  text-align: center;
  line-height: 120rpx;
}
.add-image {
  background-color: #f0f0f0;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 8rpx;
  cursor: pointer;
}
</style>
